<template>
  <view>
    <view v-if="data.length > 0">
      <view
        v-for="(item, index) in data"
        :key="index"
        class="text-sm text-dark leading-10 border-b-gray w-full relative"
        @click="select(index)"
      >
        {{ item.text
        }}<view
          class="absolute right-1 top-2"
          v-if="selectedArr.indexOf(index) !== -1"
          ><u-icon name="checkmark" size="48rpx" color="#FF3D62"></u-icon
        ></view>
      </view>
    </view>
    <view v-else class="text-center text-sm leading-8 text-gray"
      >- 暂无数据 -</view
    >
  </view>
</template>

<script>
export default {
  props: {
    data: {
      type: Array,
      default: () => {
        return [];
      },
    },
    selected: {
      type: Array,
      default: () => {
        return [];
      },
    },
    type: {
      type: String,
      default: 'single', //single单选   multiple 多选
    },
  },
  data() {
    return {
      selectedArr: [],
    };
  },
  watch: {
    selected: {
      handler(val) {
        this.selectedArr = val;
      },
    },
    selectedArr: {
      handler(val) {
        let arr = [];
        let textArr = [];
        val.forEach((el) => {
          arr.push(this.data[el].value);
          textArr.push(this.data[el].text);
        });
        this.$emit('update', arr, textArr);
      },
      deep: true,
    },
  },
  methods: {
    select(index) {
      if (this.type === 'single') {
        //单选
        if (this.selectedArr[0] !== index) {
          this.selectedArr = [];
          this.selectedArr.push(index);
        } else {
          this.selectedArr = [];
        }
      } else {
        //可多选
        let searchIndex = this.selectedArr.indexOf(index);
        if (searchIndex === -1) {
          this.selectedArr.push(index);
        } else {
          this.selectedArr.splice(searchIndex, 1);
        }
      }
    },
  },
};
</script>
<style></style>
